from flask import Flask
from flask_cors import CORS
from core.config import Config
from models.database import db
from core.plugin_manager import PluginManager

def create_app():
    """创建Flask应用实例"""
    app = Flask(__name__,
                static_folder='../static',
                template_folder='../templates')
    
    # 加载配置
    app.config.from_object(Config)
    Config.init_app(app)
    
    # 启用调试模式和自动重载
    app.config['DEBUG'] = True
    app.config['USE_RELOADER'] = True
    
    # 初始化扩展
    CORS(app, resources={
        r"/api/*": {
            "origins": ["http://localhost:5000"],
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            "allow_headers": ["Content-Type", "X-Requested-With", "Authorization"]
        }
    })
    db.init_app(app)
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    # 初始化插件管理器
    plugin_manager = PluginManager(app.config['PLUGIN_DIR'])
    plugin_manager.init_app(app)
    app.plugin_manager = plugin_manager  # 将插件管理器添加到应用实例
    
    # 注册蓝图
    from api.routes import api_bp, page_bp
    app.register_blueprint(api_bp, url_prefix='/api')
    app.register_blueprint(page_bp)
    
    @app.after_request
    def after_request(response):
        """确保响应头允许跨域访问"""
        response.headers.add('Access-Control-Allow-Origin', 'http://localhost:5000')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,X-Requested-With')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
        return response
    
    return app 